package com.srwl.mytx.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MultipleCouponReceiverItemAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by max on 16/3/27
 */
public class MultipleCouponDetailFragment extends BaseFragment {
    private static final String TAG = "MultipleCouponDetailFra";
    private static final String ARGS_COUPON_INFO = "COUPON";
    private Coupon coupon;
    private User targetUser;
    private ArrayList<Coupon> couponList = new ArrayList<>();

    private LinearLayoutManager mLayoutManager;

    private MultipleCouponReceiverItemAdapter mAdapter;

    private TextView tvUserName;
    private TextView tvGreeting;
    private TextView tvMoneyAmount;
    private TextView tvMoneyStatus;
    private ImageView ivAvatar;
    private TextView tvMoneyUse;
    private ImageView ivGroupIcon;
    private ProgressBar progressBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private int page = 1;
    private boolean hasNextPage;


    public static MultipleCouponDetailFragment newInstance(Coupon coupon) {
        MultipleCouponDetailFragment fragment = new MultipleCouponDetailFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARGS_COUPON_INFO, coupon);

        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_multiple_coupon_detail_layout, container, false);

        initViewsAndEvents(view);
        return view;
    }

    protected void initViewsAndEvents(View view) {
        if (getArguments() != null) {
            coupon = getArguments().getParcelable(ARGS_COUPON_INFO);
            targetUser = coupon.getTargetUser();

        }
        RecyclerView recyclerView = view.findViewById(R.id.money_detail_list);
        recyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new MultipleCouponReceiverItemAdapter(getActivity(), couponList);

        recyclerView.setAdapter(mAdapter);
        initView(view);
        initRefreshLayout();
        loadData(true);
    }

    private void initView(View v) {
        tvUserName = v.findViewById(R.id.tv_money_sender);
        tvGreeting = v.findViewById(R.id.tv_greeting);
        tvMoneyStatus = v.findViewById(R.id.tv_money_status);
        tvMoneyAmount = v.findViewById(R.id.tv_money_amount);
        ivAvatar = v.findViewById(R.id.iv_avatar);
        tvMoneyUse = v.findViewById(R.id.tv_money_use);
        ivGroupIcon = v.findViewById(R.id.iv_group_random);
        progressBar = v.findViewById(R.id.progress_bar);
        refreshLayout = v.findViewById(R.id.refresh_layout);
    }

    private void initRefreshLayout() {
        refreshLayout.setNestedScrollingEnabled(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                page = 1;
                loadData(false);
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", 10);
        body.put("couponId", coupon.getId());
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .getMultipleCouponReceivedRecord(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取红包记录出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取红包记录出错：" + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            if (page == 1) {
                                mAdapter.showErrorView();
                            }
                            return;
                        }

                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: " + pageInfo.toString());
                        pageInfo.getInteger("total");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }
                        List<Coupon> coupons = pageInfo.getJSONArray("list").toJavaList(Coupon.class);

                        if (coupons.size() != 0) {
                            couponList.addAll(coupons);
                            mAdapter.showNormalView();
                            page++;
                        } else if (page == 1) {
                            mAdapter.showNoDataView();
                        }


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            mAdapter.showErrorView();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }

    private void setHeaderViews(int position) {
        tvUserName.setText(targetUser.getUsername());

        //Glide.with(getActivity()).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar).into(ivAvatar);
        GlideLoadUtils.glideLoad(getActivity(), targetUser.getAvatar(), ivAvatar, R.drawable.tx_default_avatar_1);
        tvGreeting.setText(coupon.getGreeting());
        if (coupon.getAmount() == null) {//没抢到
            tvMoneyAmount.setVisibility(View.GONE);
            tvMoneyUse.setVisibility(View.GONE);
        } else {//抢到了
            tvMoneyAmount.setVisibility(View.VISIBLE);
            tvMoneyAmount.setText(String.format("￥%s", Utils.moneyFormat(coupon.getAmount())));
            tvMoneyUse.setVisibility(View.VISIBLE);
        }
        switch (coupon.getType()) {
            case Constant.COUPON_TYPE_MULTIPLE_RANDOM:
                ivGroupIcon.setVisibility(View.VISIBLE);
                ivGroupIcon.setBackgroundResource(R.drawable.rp_random_icon);
                break;
//            case Constant.RED_PACKET_TYPE_GROUP_EXCLUSIVE:
//                ivGroupIcon.setVisibility(View.VISIBLE);
//                ivGroupIcon.setBackgroundResource(R.drawable.rp_exclusive_icon);
//                break;
            default:
                ivGroupIcon.setVisibility(View.GONE);
                break;
        }
        boolean isMyCoupon = TextUtils.equals(UserProfileManager.getInstance().getLoginUserInfo().getuId(), targetUser.getuId());
        String redPacketStatus = "";
        switch (coupon.getStatus()) {
            case Constant.COUPON_STATUS_RECEIVABLE:

                if (isMyCoupon) {
                    redPacketStatus = String.format(getActivity().getString(R.string.group_money_available_sender), coupon.getReceivedCount() + "", Utils.numberFormat(coupon.getTotalCount() - coupon.getReceivedCount()), Utils.moneyFormat(coupon.getBalance()));
                } else {
                    redPacketStatus = String.format(getActivity().getString(R.string.group_money_available_receiver), coupon.getReceivedCount() + "", coupon.getTotalCount() + "");
                }
                break;
            case Constant.COUPON_STATUS_RECEIVED:
                if (coupon.getType() == Constant.COUPON_TYPE_MULTIPLE_RANDOM) {
                    if (isMyCoupon) {
                        redPacketStatus = String.format(getActivity().getString(R.string.group_money_unavailable_rand_sender), coupon.getTotalCount() + "", DateUtils.getTimeSpanWithMillis(coupon.getCreated(), coupon.getUpdated()));
                    } else {
                        redPacketStatus = String.format(getActivity().getString(R.string.group_money_unavailable_rand_receiver), coupon.getTotalCount() + "", DateUtils.getTimeSpanWithMillis(coupon.getCreated(), coupon.getUpdated()));
                    }
                } else {
                    if (isMyCoupon) {
                        redPacketStatus = String.format(getActivity().getString(R.string.group_money_unavailable_avg_receiver), coupon.getTotalCount() + "");
                    } else {
                        redPacketStatus = String.format(getActivity().getString(R.string.group_money_unavailable_avg_receiver), coupon.getTotalCount() + "");
                    }
                }
                break;
            case Constant.COUPON_STATUS_EXPIRED:
                redPacketStatus = String.format(getActivity().getString(R.string.group_money_expired), coupon.getReceivedCount() + "", Utils.numberFormat(coupon.getTotalCount() - coupon.getReceivedCount()), Utils.moneyFormat(coupon.getBalance()));
                break;
        }
        tvMoneyStatus.setText(redPacketStatus);
    }


}
